package plogg;

import java.util.HashSet;
// These will be used when the database is running
import java.sql.SQLException;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;

/*
 *  This class deals with plogg specific database actions but can use a more generic database connection class if that makes sense.
 *  
 *  Package private. All external interactions are done through plogg.Plogg
 */


public class Database {
	
	private static Connection connect;
	private static Statement statement;
	
	// Stub function should return all appropriate Plogg IDs
	public static HashSet<String> getAllDevices()	{
		HashSet<String> fakelist = new HashSet<String>();
		fakelist.add("b1:00:12:a5:5b");
		fakelist.add("e1:00:00:a5:5b");
		fakelist.add("e1:00:22:a6:5b");
		return fakelist;
	}
	
	/**
	 * Connects to the database
	 */
	public static void connectToDatabase() {
		
		try {
			String url = "jdbc:sqllite:Plogg.db";
			Class.forName("org.sqlite.JDBC");
			connect = DriverManager.getConnection(url);
			statement = connect.createStatement();
			
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
	}
	
	/**
	 * Sets up the database itself. It is assumed that
	 * if this program was to ship out, the database would 
	 * need creating first??
	 */
	private static void setupDatabase() throws SQLException {
		
		String createDatabaseSQL = "";
		PreparedStatement prepStatement = null;
		
		createDatabaseSQL += "CREATE TABLE Plogg (";
		createDatabaseSQL += "PloggID VARCHAR2(14) NOT NULL PRIMARY KEY,";
		createDatabaseSQL += "PloggName VARCHAR(25),";
		createDatabaseSQL += "LogInterval NUMBER(5))";
			
		createDatabaseSQL = "CREATE TABLE LogEntry (";
		createDatabaseSQL += "PloggID VARCHAR2(14) NOT NULL REFERENCES Plogg(PloggID),";
		createDatabaseSQL += "Date DATE NOT NULL,";
		createDatabaseSQL += "Time TIME NOT NULL,";
		createDatabaseSQL += "Cost NUMBER(5,2),";
		createDatabaseSQL += "Power NUMBER(5,2) NOT NULL)";
		
		prepStatement = connect.prepareStatement(createDatabaseSQL);
		prepStatement.addBatch("COMMIT");
		connect.setAutoCommit(false);
		prepStatement.executeBatch();
	}
		
	/**
	 * Gets a reading for a particular time from the database
	 * @param startDate Starting date
	 * @param startTime Starting time
	 * @param endDate Ending date
	 * @param endTime Ending time 
	 */
	public static void getReadingForTime(String startDate, String startTime, 
			String endDate, String endTime) {

		/* Will be updated as we continue learning SQL */
		//PreparedStatement prepStatement = connect.prepareStatement();

	}

}